package com.kuaimacode.kframework.admin.services.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.andyczy.java.excel.ExcelUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.admin.vo.request.OrderReq;
import com.kuaimacode.kframework.common.Constant;
import com.kuaimacode.kframework.mybatis.mapper.user.OrderMapper;
import com.kuaimacode.kframework.mybatis.models.user.Order;
import com.kuaimacode.kframework.util.DateUtil;
import com.kuaimacode.kframework.util.DictUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author 中元
 * @date 2019/03/18
 */
@Service
public class  OrderService extends ServiceImpl<OrderMapper, Order> {

    	/**
    	 *  分页查找所有的数据
    	 * @param pageNum 当前页码，从1开始
    	 * @param pageSize  一页显示多少行
    	 * @return
    	 */
    	public PageInfo<Order> findAll(int pageNum, int pageSize) {
    		PageHelper.startPage(pageNum, pageSize);
    		List<Order> datas = baseMapper.selectList(null);
    		return new PageInfo<Order>(datas);
    	}

	/**
	 *  分页查找所有的数据(按条件)
	 * @param pageNum 当前页码，从1开始
	 * @param pageSize  一页显示多少行
	 * @return
	 */
	public PageInfo<Order> findAll(int pageNum, int pageSize, OrderReq order) {
		PageHelper.startPage(pageNum, pageSize);
		QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        Optional.ofNullable(order.getAgentId()).filter(str->!"".equals(str)).ifPresent(str->queryWrapper.eq("agent_id",str));
		Optional.ofNullable(order.getOrderNo()).filter(str->!"".equals(str)).ifPresent(str->queryWrapper.eq("order_no",str));
		Optional.ofNullable(order.getType()).ifPresent(str->queryWrapper.eq("type",str));
		Optional.ofNullable(order.getChildType()).ifPresent(str->queryWrapper.eq("child_type",str));
		Optional.ofNullable(order.getStatus()).ifPresent(str->queryWrapper.eq("status",str));
		Optional.ofNullable(order.getPayType()).ifPresent(str->queryWrapper.eq("pay_type",str));
		Optional.ofNullable(order.getEndDate()).ifPresent(str->queryWrapper.le("create_at",str));
		Optional.ofNullable(order.getStartDate()).ifPresent(str->queryWrapper.ge("create_at",str));
        Optional.ofNullable(order.getMasterId()).ifPresent(str->queryWrapper.ge("master_id",str));
        queryWrapper.orderByDesc("id");//降序
		List<Order> datas = baseMapper.selectList(queryWrapper);
		return new PageInfo<Order>(datas);
	}

    /**
     *  分页查找所有的数据(按条件)
     * @param pageNum 当前页码，从1开始
     * @param pageSize  一页显示多少行
     * @return
     */
    public PageInfo<Order> partnerOrderList(int pageNum, int pageSize, OrderReq order) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        Optional.ofNullable(order.getStatus()).filter(status -> status != 0).ifPresent(str->queryWrapper.eq("status",str));
        Optional.ofNullable(order.getEndDate()).ifPresent(str->queryWrapper.le("create_at",str));
        Optional.ofNullable(order.getStartDate()).ifPresent(str->queryWrapper.ge("create_at",str));
        queryWrapper.eq("has_partner", 1);
        queryWrapper.eq("user_id", order.getUserId());
        queryWrapper.orderByDesc("id");//降序
        List<Order> datas = baseMapper.selectList(queryWrapper);
        return new PageInfo<Order>(datas);
    }

    /**
     * 合作商家订单导出
     * @param order
     * @param response
     */
    public void partnerOrderExport(OrderReq order, HttpServletResponse response) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        Optional.ofNullable(order.getStatus()).filter(status -> status != 0).ifPresent(str -> queryWrapper.eq("status", str));
        Optional.ofNullable(order.getEndDate()).ifPresent(str -> queryWrapper.le("create_at", str));
        Optional.ofNullable(order.getStartDate()).ifPresent(str -> queryWrapper.ge("create_at", str));
        queryWrapper.eq("has_partner", 1);
        queryWrapper.eq("user_id", order.getUserId());
        List<Order> datas = baseMapper.selectList(queryWrapper);

        List<List<String[]>> dataLists = new ArrayList<>();
        List<String[]> oneList = new ArrayList<>();
        String[] headers = {"序号", "分站ID", "订单号", "金额", "订单状态", "发单时间", "支付类型"};

        oneList.add(headers);
        Map<String, String> orderStatusMap = DictUtil.keyValueList("ORDER_STATUS");
        Map<String, String> orderPayMap = DictUtil.keyValueList("PAY_TYPE");
        datas.forEach(ord -> {
            String[] values = new String[]{ord.getId().toString(), ord.getAgentId(),
                    ord.getOrderNo(), ord.getAmount().toString(), orderStatusMap.get(ord.getStatus().toString()),
                    DateUtil.dateToString(ord.getCreateAt(), DateUtil.FORMAT_ONE), ord.getPayType() == null ? "" : orderPayMap.get(ord.getPayType().toString())
            };
            oneList.add(values);
        });
        dataLists.add(oneList);

        ExcelUtils excelUtils = ExcelUtils.initialization();
        excelUtils.setDataLists(dataLists);
        excelUtils.setSheetName(new String[]{"订单列表"});
        excelUtils.setResponse(response);
        // 执行导出
        excelUtils.exportForExcelsOptimize();
    }

    /**
     * 今日订单数
     * @return
     */
	public int todayOrderCount() {
	    QueryWrapper<Order> wrapper = new QueryWrapper<>();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime beginTime = now.withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endTime = now.withHour(23).withMinute(59).withSecond(59);

	    wrapper.between("create_at", beginTime, endTime);
	    return baseMapper.selectCount(wrapper);
    }

    /**
     * 今日订单金额
     * @return
     */
    public long todayOrderAmount() {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime beginTime = now.withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endTime = now.withHour(23).withMinute(59).withSecond(59);

        wrapper.between("create_at", beginTime, endTime);
        List<Order> orders = baseMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(orders)) {
            return 0;
        }
        BigDecimal amount = new BigDecimal(0);
        for (Order order : orders) {
            amount = amount.add(order.getAmount());
        }
        return amount.longValue();
    }

    /**
     * 获取最新的订单
     * @return
     */
    public List<Order> top10Order() {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_at");
        PageHelper.startPage(1, 10);
        return baseMapper.selectList(wrapper);
    }

    /**
     * 查询用户订单数
     * @param userId
     * @return
     */
    public long userOrderCount(Long userId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return baseMapper.selectCount(wrapper);
    }

    /**
     * 查询某日有效订单数量
     * param date yyyy-MM-dd
     * param type 1-跑腿 2-其他
     * @return
     */
    public BigDecimal dayOrderAmount(String date, Integer type) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        Date beginTime = DateUtil.stringtoDate(date+" 00:00:00", DateUtil.FORMAT_ONE);
        Date endTime = DateUtil.stringtoDate(date+" 23:59:59", DateUtil.FORMAT_ONE);

        wrapper.between("create_at", beginTime, endTime);

        Integer[] status = {2,3,4,5,6,7};//服务中、取货中、送货中
        wrapper.in("status", status);

        if(type == 1){
            //跑腿
            wrapper.eq("type", 1);
        }else if(type == 2){
            //技术服务
            wrapper.ne("type", 1);
        }

        List<Order> orders = baseMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(orders)) {
            return BigDecimal.ZERO;
        }
        BigDecimal amount = new BigDecimal(0);
        for (Order order : orders) {
            amount = amount.add(order.getAmount());
        }
        return amount;
    }

    /**
     * 查询某日有效订单数量
     * param date yyyy-MM-dd
     * param type 1-跑腿 2-其他
     * @return
     */
    public long dayOrderCount(String date, Integer type) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        Date beginTime = DateUtil.stringtoDate(date+" 00:00:00", DateUtil.FORMAT_ONE);
        Date endTime = DateUtil.stringtoDate(date+" 23:59:59", DateUtil.FORMAT_ONE);

        wrapper.between("create_at", beginTime, endTime);

        Integer[] status = {2,3,4,5,6,7};//服务中、取货中、送货中
        wrapper.in("status", status);

        if(type == 1){
            //跑腿
            wrapper.eq("type", 1);
        }else if(type == 2){
            //技术服务
            wrapper.ne("type", 1);
        }

        return baseMapper.selectCount(wrapper);
    }

    /**
     * 交易总额
     * @return
     */
    public BigDecimal totalOrderAmount() {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.ne("status", Constant.OrderStatusEnum.CANCLE.getCode());

        List<Order> orders = baseMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(orders)) {
            return BigDecimal.ZERO;
        }
        BigDecimal amount = new BigDecimal(0);
        for (Order order : orders) {
            amount = amount.add(order.getAmount());
        }
        return amount;
    }


    /**
     * 未入账金额额
     * @return
     */
    public BigDecimal totalUnInAmount() {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
       // wrapper.ne("status", Constant.OrderStatusEnum.CANCLE.getCode());
        Integer[] status = {3,4,5};//服务中、取货中、送货中
        wrapper.in("status", status);

        List<Order> orders = baseMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(orders)) {
            return BigDecimal.ZERO;
        }
        BigDecimal amount = new BigDecimal(0);
        for (Order order : orders) {
            amount = amount.add(order.getAmount());
        }
        return amount;
    }
}

